import Immutable from 'immutable'
import {getformdatas} from './reqUtil'

export const realLength = (str) => {
	let j = 0;
	for(var i = 0; i <= str.length - 1; i++) {
		j = j + 1;
		if((str.charCodeAt(i)) > 127) {
			j = j + 2;
		}
	}
	return j;
}

window.realLength = realLength;

export const checkLength =(str,strLen,elMaxLen) =>{
	if(strLen <= elMaxLen) {
		return str;
	}
	
	let j = 0;
	for(var i = 0; i <= str.length - 1; i++) {
		j = j + 1;
		if((str.charCodeAt(i)) > 127) {
			j = j + 2;
		}
		
		if(j > elMaxLen){
			return str.substring(0,i);
		}
		
		if(j == elMaxLen) {
			return str.substring(0,i+1);
		}
	}
	return str;
}

window.checkLength = checkLength;

const resetWorkflow = (url, title, type) => {
	if(type == '3') {
		openFullWindowHaveBar(url);
		return;
	} else if(type == '1' || type == '2') {
		url = "/workflow/request/WFReset.jsp?wfid=" + url + "&type=" + type;
		title = '流转设置';
	}
	dialog = new window.top.Dialog();
	dialog.currentWindow = window;
	dialog.Title = title;
	dialog.Width = 1020;
	dialog.Height = 580;
	dialog.Drag = true;
	dialog.maxiumnable = false;
	dialog.URL = url;
	dialog.show();
}

window.resetWorkflow = resetWorkflow;

//生成系统提醒流程
const triggerSystemWorkflow = (prefix, url, title, loginuserid, type) => {
	const requestid = window.store_e9_workflow.getState().workflowReq.getIn(['params','requestid'])
	prefix = prefix.replace(/~0~/g, "<span class='importantInfo'>");
	prefix = prefix.replace(/~1~/g, "</span>");
	prefix = prefix.replace(/~2~/g, "<span class='importantDetailInfo'>");
	var infohtml = jQuery('.message-detail').html();
	if(!infohtml) {
		infohtml = "";
	} else {
		infohtml = "<div class='message-detail'>" + infohtml + "</div>";
	}
	var botfix = '进行设置';
	if('流程干预' == title) {
		botfix = '流程干预';
	}
	var messagedetail = infohtml + '<span>' + prefix + '，请<a id="wfSErrorResetBtn" style="color:#2b8ae2!important;" href="' + url + '" title="' + title + '" type="' + type + '"> 点击这里 </a>' + botfix + '</span>';
	var ahtml = jQuery('.message-bottom span').html();
	jQuery('<span> 点击这里 <span>').replaceAll('.message-bottom .sendMsgBtn');
	jQuery.ajax({
		type: 'post',
		url: '/workflow/request/TriggerRemindWorkflow.jsp?_' + new Date().getTime() + "=1",
		data: {
			remark: messagedetail,
			loginuserid: loginuserid,
			requestid: requestid
		},
		error: function(XMLHttpRequest, textStatus, errorThrown) {
			jQuery('.message-bottom span').html(ahtml);
		},
		success: function(data, textStatus) {
			window.top.Dialog.alert('已成功向管理员发送提醒流程');
		}
	});
}

window.triggerSystemWorkflow = triggerSystemWorkflow;

//重新选择操作者
const rechoseoperator = () => {
	var eh_dialog = null;
	if(window.top.Dialog)
		eh_dialog = new window.top.Dialog();
	else
		eh_dialog = new Dialog();
	eh_dialog.currentWindow = window;
	eh_dialog.Width = 650;
	eh_dialog.Height = 500;
	eh_dialog.Modal = true;
	eh_dialog.maxiumnable = false;
	eh_dialog.Title = '请选择';
	eh_dialog.URL = "/workflow/request/requestChooseOperator.jsp";
	eh_dialog.callbackfun = function(paramobj, datas) {
		let chrostoperatorinfo = {
			eh_setoperator:'y',
			eh_relationship:datas.relationship,
			eh_operators:datas.operators
		};
		window.store_e9_workflow.dispatch(window.action_e9_workflow.WorkflowReqAction.updateSubmitParams(chrostoperatorinfo));
		window.store_e9_workflow.dispatch(window.action_e9_workflow.WorkflowReqAction.doSubmitApi({actiontype:"requestOperation",src:"submit"}));
	};
	eh_dialog.closeHandle = function(paramobj, datas) {
		const eh_setoperator = window.store_e9_workflow.getState().workflowReq.get('submitParams').get('eh_setoperator');
		if(eh_setoperator != 'y'){
			window.store_e9_workflow.dispatch(window.action_e9_workflow.WorkflowReqAction.updateSubmitParams({eh_setoperator:'n'}));
			window.store_e9_workflow.dispatch(window.action_e9_workflow.WorkflowReqAction.doSubmitApi({actiontype:"requestOperation",src:"submit"}));
		}
	};
	eh_dialog.show();
}

window.rechoseoperator = rechoseoperator;

const showAllReceiveUser = () =>{
	const _m = jQuery('.message-box .message-detail');
    const allReceiveUserName = _m.find('#message-all-receive-user').val();
    const currentUserName = _m.find('div span').text();
    const isShowAll = _m.find('i').hasClass("anticon-down");
    _m.find("div span").text(allReceiveUserName);
    _m.find("#message-all-receive-user").val(currentUserName);
    if(isShowAll){
        _m.find('i').removeClass("anticon-down");
        _m.find('i').addClass("anticon-up");
	}else{
        _m.find('i').removeClass("anticon-up");
        _m.find('i').addClass("anticon-down");
	}
}
window.showAllReceiveUser = showAllReceiveUser;

const showDetail = (targetele, fieldid) => {
    showAutoCompleteDiv(targetele, fieldid);
}
window.showDetail = showDetail;

const showAutoCompleteDiv = (ele, fieldid) => {
	jQuery("#__brow__detaildiv").remove();

	var target = jQuery(ele);
	var offset = target.offset();
	var scrollObj = jQuery("div.wea-new-top-req-content");
	
	var __x = offset.left - 245/2 +  jQuery(ele).width()/2;
	var __y = offset.top + scrollObj.scrollTop() - scrollObj.offset().top + 5;
	if (jQuery(ele).height() > 20) {
		__x = offset.left - 245/2 + 5;
		__y = __y + 18;
	}
	
	var separator = ",";
	
	var _ids = target.attr("_ids");
	var _names = target.attr("_names");
	var _jobtitles = target.attr("_jobtitles");
	
	var _idArray = _ids.split(separator);
	var _nameArray = _names.split(separator);
	var _jobtitleArray = _jobtitles.split(separator);
	var browgroupHtml = "";
	var _i;
	for (_i=0; _i<_idArray.length; _i++) {
		var className=(_i%2==1?"ac_even":"ac_odd");
		var displaycss = _i > 4 ? " display:none; " : "";
		var resdetailinfohtml = "<span style='display:inline-block;width:80px;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;'><a href=javaScript:openhrm(" + _idArray[_i] + "); onclick='pointerXY(event);' style='overflow: hidden;white-space: nowrap;text-overflow: ellipsis;' title='" + _nameArray[_i] + "'>" + _nameArray[_i] + "</a></span>";
		resdetailinfohtml += "<span style='float:right;display:inline-block;width:130px;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;' title='" + _jobtitleArray[_i] + "'>" + _jobtitleArray[_i] + "</span>";
		
		browgroupHtml += '<li class="'+className+'" _id="'+_idArray[_i]+'" style=\'' + displaycss + '\'>' + resdetailinfohtml +'</li>';
		
		
		
		if (_i > 4 && _i == _idArray.length-1) {
			browgroupHtml += '<li class="'+className+'" title="显示全部" style="text-align:center;" onclick="showalldetail(this, ' + fieldid + ');">显示全部</li>';
		}
	}
	
	if(!!browgroupHtml){
		var autoCompleteDiv = jQuery("<div id='__brow__detaildiv' class='wea-hrmgroup-wrapper' style=\"position:absolute;width:245px;z-index:999;left:" + __x + "px;top:" + __y + "px;\"></div>");
		var autoCompleteDiv_html = jQuery("<div class=\"arrowsblock\"><img src=\"/images/ecology8/workflow/multres/arrows_2_wev8.png\" width=\"22px\" height=\"22px\"></div>"
			+ "<div class='ac_results' style='margin-top:20px;background:#fff;z-index:9;'><ul>"+browgroupHtml+"</ul></div>"
		);
		autoCompleteDiv.append(autoCompleteDiv_html);
		//autoCompleteDiv_html.addClass("ac_results");
         jQuery("div.wea-popover-hrm-relative-parent").append(autoCompleteDiv);
	}
}

const showalldetail = (ele, fieldid) => {
	var target = jQuery(ele);
	var parentDiv = target.closest("div");
	parentDiv.css({
	    "height":parentDiv.height() + "px",
		"overflow" : "auto"
	});
	
	//parentDiv.perfectScrollbar({horizrailenabled:false,zindex:1000});
	
	var othli = target.parent().children().not(":visible");
	othli.show();
	target.hide();
}

window.showalldetail = showalldetail;

jQuery(function () {
	jQuery("table.excelMainTable").live('mouseup', function (e) {
		if (jQuery("#__brow__detaildiv").is(":visible") && !!!jQuery(e.target).closest("#__brow__detaildiv")[0]) {
			jQuery("#__brow__detaildiv").hide();
		}
		if (jQuery("#_browcommgroupblock").is(":visible") && !!!jQuery(e.target).closest("#_browcommgroupblock")[0]) {
			jQuery("#_browcommgroupblock").hide();
		}
		e.stopPropagation();
	});
});


//Iframe区域相关方法
window.iframeOperate = (function(){
	
	function showIframeArea(vthis){
		jQuery(vthis).closest("td").find(".iframeLoading").hide();
		jQuery(vthis).show();
	}
	
	//Iframe区域高度自适应高度
	function autoAdjustHeight(vthis){
		var iframeObj = jQuery(vthis);
		var funObj = function(){autoAdjustHeight(vthis)};
		var eachcount = parseInt(iframeObj.attr("eachcount"));
		if(eachcount > 10){
			iframeObj.css("height", "100px");
			return;
		}
		
		var contextObj = iframeObj[0].contentWindow.document;
		var bodyContentHeight = contextObj.body.scrollHeight;
		//if(window.console) console.log("scrollHeight:"+bodyContentHeight+"  |offsetHeight:"+contextObj.body.offsetHeight)
		if(bodyContentHeight == 0){
			iframeObj.attr("eachcount", eachcount+1);
			window.setTimeout(funObj, 500);
		}else{
			iframeObj.css("height", bodyContentHeight+"px");
		}
	}

	return{
		//Iframe区域onload事件
		loadingOver: function(vthis){
			if(jQuery(vthis).attr("adjustheight") == "y"){
				window.setTimeout(function(){
					showIframeArea(vthis);
					autoAdjustHeight(vthis);
				},800);
			}else{
				showIframeArea(vthis);
			}
		}
	}
})();

//二维码、条形码相关方法
window.scancodeOperate = (function(){

	function adjustSize_scancode(vthis){
		try{
			var parentHeight = vthis.closest("td").height();
			var curHeight = vthis.height();
			//if(window.console)console.log("二维码/条形码宽度调整:"+parentHeight+"  |  "+curHeight);
			if(parseInt(parentHeight)-parseInt(curHeight) > 8)		//td高度会包含图片高度及上边框高度，避免死循环触发
				vthis.css("height", parentHeight);
		}catch(e){}
	}
	
	return {
		//ready触发自适应单元格大小（针对所在行存在高度渐变时，故绑定个resize）
		readyAdjustSize: function(){
			window.setTimeout(function(){
				jQuery(".qrcodeimg,.barcodeimg").each(function(){
					var vthis = jQuery(this);
					vthis.resize(function(){
						adjustSize_scancode(vthis);
					});
					adjustSize_scancode(vthis);
				});
			},100);
		}
	}
})();

//文档、附件打开加log的方法，调用的dwr先屏蔽
window.addDocReadTag = (docId) =>{
	//DocReadTagUtil.addDocReadTag(docId,<%=user.getUID()%>,<%=user.getLogintype()%>,"<%=request.getRemoteAddr()%>",returnTrue);
}

//系统提醒工作流需要相关JS
const sysWfUtil = {
	readyHandle: function(){
		const url = jQuery('#wfSErrorResetBtn').attr('href');
		const title = jQuery('#wfSErrorResetBtn').attr('title');
		const type = jQuery('#wfSErrorResetBtn').attr('type');
		jQuery('#wfSErrorResetBtn').attr('href','javascript:void(0)').removeAttr('target').removeAttr('title');
		jQuery('#wfSErrorResetBtn').attr('onclick',"sysWfUtil.resetWorkflowCfg('"+url+"','"+title+"','"+type+"')");
		jQuery('.condition').css('color','#123885');
		jQuery("#wfSErrorResetBtn").removeAttr('style');
	},
	resetWorkflowCfg: function(url,title,type){
		if(type == '3'){
			openFullWindowHaveBar(url);
			return;
		}else if(type == '1'||type =='2'){
			url = "/workflow/request/WFReset.jsp?wfid="+url+"&type="+type;
			title = '流转设置';
		}
		const dialog = new window.top.Dialog();
		dialog.currentWindow = window;
		dialog.Title = title;
		dialog.Width = 1020;
		dialog.Height = 580;
		dialog.Drag = true;
		dialog.maxiumnable = false;
		dialog.URL = url;
		dialog.show();
	}
}
window.sysWfUtil = sysWfUtil;